package com.zhaokuo.filter;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.zhaokuo.dto.SessionDTO;
import com.zhaokuo.util.Constants;


public class CheckLoginFilter extends AbstractFilter{
	private static final Set<String> unfilterUrls =  new HashSet<String>();
	
	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws ServletException, IOException {
		HttpServletRequest request = (HttpServletRequest)req;
		HttpServletResponse response = (HttpServletResponse)res;
		HttpSession session = request.getSession();
		SessionDTO sessionDTO = session == null?null:(SessionDTO)session.getAttribute(Constants.SESSIONDTO);
		if(sessionDTO == null&& checkRequiredFilter(request)){
			String service = constructRedirectUrl(request, response, true,request.getMethod());
			response.sendRedirect(Constants.LOGIN_URL + "?service="+service);
			return;
		}
		chain.doFilter(request, response);
	}
	
	public static  boolean checkRequiredFilter(HttpServletRequest request) {
		String url  = request.getRequestURL().toString();
		for (String s:unfilterUrls) {
			if (url.indexOf(s) !=  -1) {
				return false;
			}
		}
		return true;
	}
	
	public static Set<String> getUnfilterurls() {
		return unfilterUrls;
	}
	public void destroy() {}
	
	public void init(FilterConfig config) throws ServletException {
		String urlStr = null;
		try {
			urlStr = config.getInitParameter("uncheckLoginUrls");
		 if (urlStr != null) {
			 String [] urls  = urlStr.split(",");
			 for (String s:urls) {
				 unfilterUrls.add(s.trim());
			 }
		 }
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	

}
